package com.free.bsf.message.channel;

import com.fasterxml.jackson.core.type.TypeReference;
import com.free.bsf.core.http.DefaultHttpClient;
import com.free.bsf.core.http.HttpClient;
import lombok.Data;
import org.apache.http.entity.ContentType;

import java.net.SocketTimeoutException;


/**
 * @author: huojuncheng
 * @version: 2020-08-25 15:10
 **/
@Data
public class QiYeWeiXinProvider extends AbstractMessageProvider {
    @Override
    protected String getName(){
        return "qiyeweixin";
    }

    String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={access_token}";

    @Override
    public void sendText(String text){
        if(!isEnabled())
            return;
        getTokens().forEach(t-> {
            String api = url.replace("{access_token}", t);
            MessageReq reqContent = new MessageReq();
            Content txt = new Content();
            txt.setContent(text);
            reqContent.setMsgtype("text");
            reqContent.setText(txt);
            try {
                HttpClient.Params params = HttpClient.Params.custom().setContentType(ContentType.APPLICATION_JSON).add(reqContent).build();
                DefaultHttpClient.Default.post(api, params, new TypeReference<WechatResponse>() {
                });
            } catch (Exception e) {
                if (e.getCause() instanceof SocketTimeoutException) {
                    //网关不一定稳定
                    return;
                }
                throw e;
            }
        });
    }

    @Data
    public static class WechatResponse {
        private Integer errcode;
        private String errmsg;
    }

    @Data
    public static class MessageReq {
        private String msgtype;
        private Content text;
    }
    @Data
    public class Content {
        private String content;
    }
}
